package com.outsider.util.music;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.outsider.util.OkHttp3;

import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

public class BaiduMusic {
	private static final String SEARCH_URL = "http://musicmini.baidu.com/app/search/searchList.php?ie=utf-8&page=0&qword=";

	public static List<Music> search(String name) {
		List<Music> result = new ArrayList<>();
		OkHttp3 okHttp3=OkHttp3.getInstance();
		String body=okHttp3.get(SEARCH_URL+name);
		Html html=new Html(body);
		List<Selectable> list=html.xpath("//*[@id=\"sc-table\"]/tbody/tr").nodes();
		//只提取前10条
		for (int i=2;i<=Math.min(list.size()-1, 12);i++){
			Music music=new Music();
			Selectable node=list.get(i);
			music.setID(node.xpath("//input/@id").get());
			String temp=node.xpath("//*[@class=\"sName\"]/div/a/em/text()").get();
			if (temp==null)
				temp=node.xpath("//*[@class=\"sName\"]/div/a/text()").get();
			if (temp==null) continue;
			music.setName(temp);
			music.setSinger(node.xpath("//*[@class=\"uName\"]/div/a/@title").get());
			music.setAlbum(node.xpath("//*[@class=\"aName\"]/a/text()").get());
			music.setPlaytime(0);
			music.setSource(Music.SOURCE_BAIDU);
			result.add(music);
		}
		
		return result;
	}
	private static final String Deatil_URL="http://ting.baidu.com/data/music/links?songIds=";
	public static String getURL(String ID) {
		OkHttp3 okHttp3=OkHttp3.getInstance();
		String body=okHttp3.get(Deatil_URL+ID);
		
		JSONObject json=JSONObject.parseObject(body);
		if (json.getInteger("errorCode")!=22000) return null;
		else return json.getJSONObject("data").getJSONArray("songList").getJSONObject(0).getString("songLink");
	}
	
	public static void main(String args[]) {
		List<Music> list=BaiduMusic.search("银临");

		
		
	}
}
